from django.db import models
from django.utils import timezone
import time


# 管理员表
class FaAdmin(models.Model):
    STATUS_CHOICES = [
        ('normal', '正常'),
        ('locked', '锁定'),
        ('disabled', '禁用'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    username = models.CharField(
        max_length=20,
        unique=True,
        default='',
        verbose_name='用户名'
    )
    nickname = models.CharField(
        max_length=50,
        default='',
        verbose_name='昵称'
    )
    password = models.CharField(
        max_length=32,
        default='',
        verbose_name='密码'
    )
    salt = models.CharField(
        max_length=30,
        default='',
        verbose_name='密码盐'
    )
    avatar = models.CharField(
        max_length=255,
        default='',
        verbose_name='头像'
    )
    email = models.CharField(
        max_length=100,
        default='',
        verbose_name='电子邮箱'
    )
    mobile = models.CharField(
        max_length=11,
        default='',
        verbose_name='手机号码'
    )
    loginfailure = models.PositiveSmallIntegerField(
        default=0,
        verbose_name='失败次数'
    )
    logintime = models.BigIntegerField(
        null=True,
        blank=True,
        verbose_name='登录时间'
    )
    loginip = models.CharField(
        max_length=50,
        null=True,
        blank=True,
        verbose_name='登录IP'
    )
    createtime = models.BigIntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.BigIntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )
    token = models.CharField(
        max_length=59,
        default='',
        verbose_name='Session标识'
    )
    status = models.CharField(
        max_length=30,
        choices=STATUS_CHOICES,
        default='normal',
        verbose_name='状态'
    )

    class Meta:
        db_table = 'fa_admin'
        verbose_name = '管理员'
        verbose_name_plural = '管理员'


    def save(self, *args, **kwargs):
        # 自动设置时间戳
        now = int(time.time())
        if not self.createtime:
            self.createtime = now
        self.updatetime = now

        # 密码加密逻辑（示例）
        if not self.salt:
            import random
            import string
            self.salt = ''.join(random.choice(string.ascii_letters + string.digits) for _ in range(6))
            # 这里应该添加实际的密码加密逻辑
            # self.password = some_hash_function(self.password + self.salt)

        super().save(*args, **kwargs)

    @property
    def login_datetime(self):
        """将时间戳转为可读格式"""
        from datetime import datetime
        return datetime.fromtimestamp(self.logintime) if self.logintime else None


# 管理员分组表
class FaAuthGroup(models.Model):
    STATUS_CHOICES = [
        ('normal', '正常'),
        ('disabled', '禁用'),
        ('', '未设置'),
    ]

    id = models.AutoField(primary_key=True, verbose_name='ID')
    pid = models.PositiveIntegerField(
        default=0,
        verbose_name='父组别ID'
    )
    name = models.CharField(
        max_length=100,
        default='',
        verbose_name='组名'
    )
    rules = models.TextField(
        verbose_name='规则ID',
        help_text='多个规则ID用逗号分隔'
    )
    createtime = models.BigIntegerField(
        null=True,
        blank=True,
        verbose_name='创建时间'
    )
    updatetime = models.BigIntegerField(
        null=True,
        blank=True,
        verbose_name='更新时间'
    )
    status = models.CharField(
        max_length=30,
        choices=STATUS_CHOICES,
        default='',
        verbose_name='状态'
    )

    class Meta:
        db_table = 'fa_auth_group'
        verbose_name = '权限分组'
        verbose_name_plural = '权限分组'
        indexes = [
            models.Index(fields=['pid']),
            models.Index(fields=['status']),
        ]

    def __str__(self):
        return f"{self.name} (ID:{self.id})"

    def save(self, *args, **kwargs):
        # 自动设置时间戳
        now = int(time.time())
        if not self.createtime:
            self.createtime = now
        self.updatetime = now

        # 清理规则格式
        if self.rules:
            self.rules = ','.join([str(rule_id).strip() for rule_id in self.rules.split(',') if str(rule_id).strip()])

        super().save(*args, **kwargs)

    @property
    def rules_list(self):
        """将规则字符串转为列表"""
        return [int(rule_id) for rule_id in self.rules.split(',') if rule_id]

    @property
    def create_datetime(self):
        """时间戳转datetime"""
        from datetime import datetime
        return datetime.fromtimestamp(self.createtime) if self.createtime else None


# 管理员分组关联表
class FaAuthGroupAccess(models.Model):
    id = models.AutoField(primary_key=True, verbose_name='ID')
    uid = models.PositiveIntegerField(verbose_name='管理员ID')
    group_id = models.PositiveIntegerField(verbose_name='分组ID')

    class Meta:
        db_table = 'fa_auth_group_access'
        verbose_name = '权限分组关联'
        verbose_name_plural = '权限分组关联'
        unique_together = (('uid', 'group_id'),)  # 联合唯一约束
        indexes = [
            models.Index(fields=['uid'], name='uid_idx'),
            models.Index(fields=['group_id'], name='group_id_idx'),
        ]

    def __str__(self):
        return f"用户{self.uid}-组{self.group_id}"


# 日志记录
class FaAdminLog(models.Model):
    id = models.AutoField(
        primary_key=True,
        verbose_name='ID'
    )
    admin_id = models.PositiveIntegerField(
        default=0,
        verbose_name='管理员ID'
    )
    username = models.CharField(
        max_length=30,
        default='',
        verbose_name='管理员名字'
    )
    url = models.CharField(
        max_length=1500,
        default='',
        verbose_name='操作页面'
    )
    title = models.CharField(
        max_length=100,
        default='',
        verbose_name='日志标题'
    )
    content = models.TextField(
        verbose_name='内容'
    )
    ip = models.CharField(
        max_length=50,
        default='',
        verbose_name='IP地址'
    )
    useragent = models.CharField(
        max_length=255,
        default='',
        verbose_name='User-Agent'
    )
    createtime = models.BigIntegerField(
        verbose_name='操作时间',
        default=int(time.time()),
        null=True
    )

    class Meta:
        db_table = 'fa_admin_log'
        verbose_name = '管理员日志'
        verbose_name_plural = '管理员日志'
        indexes = [
            models.Index(fields=['username'], name='name_idx'),
            models.Index(fields=['admin_id']),
        ]

    def __str__(self):
        return f"{self.username} - {self.title}"
